package com.mc.read.pcApi.filter;

import com.alibaba.fastjson.JSON;
import com.mc.read.common.emun.ServiceCodeEnum;
import com.mc.read.common.exception.ServiceException;
import com.mc.read.dao.mapper.UserinformationMapper;
import com.mc.read.dao.models.Userinformation;
import com.mc.read.vo.request.BaseRequest;
import com.mc.read.vo.respose.BaseRespose;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:LiuHao
 * @Date: Create in 12:13 2017/11/10
 **/

@Slf4j
//@WebFilter(urlPatterns ={"/verify/*"})
public class PermissionsFilter implements Filter {
    @Autowired
    UserinformationMapper userinformationMapper;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("app token验证过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
        ServletRequest requestWrapper = null;
        BaseRespose baseResponse=new BaseRespose();
        try {
            String temp = "";
            String decryptStr = "";
            try {
            requestWrapper = new BodyReaderServletWrapper((HttpServletRequest) servletRequest);
                if(!ObjectUtils.isEmpty(requestWrapper)) {
                    BufferedReader br = requestWrapper.getReader();
                    while ((temp = br.readLine()) != null) {
                        decryptStr = decryptStr + temp;
                    }
                }
            } catch (NullPointerException e) {
                return;
            }
            if(ObjectUtils.isEmpty(decryptStr)){
                return;
            }
            System.out.println(decryptStr);
            BaseRequest baseRequest= JSON.parseObject(decryptStr, BaseRequest.class);
            log.info("请求参数为{}",baseRequest);
            if(ObjectUtils.isEmpty(baseRequest.getToken())|| ObjectUtils.isEmpty(baseRequest.getUserId())){
                throw new ServiceException(ServiceCodeEnum.SIGN_IS_FAILURE);
            }
            Userinformation userinformation=userinformationMapper.selectByPrimaryKey(baseRequest.getUserId());
            if(ObjectUtils.isEmpty(userinformation)){
                throw new ServiceException(300,"未找到该用户");
            }
            if(-1==userinformation.getStaus()){
                throw new ServiceException(300,"该用户已被禁用");
            }
            if(!(baseRequest.getToken().equals(userinformation.getToken()))){
                throw new ServiceException(300,"该账号疑在另一设备登录");
            }
            filterChain.doFilter(requestWrapper, servletResponse);
            return;
        }
        catch (ServiceException e){
            e.printStackTrace();
            baseResponse.setCode(e.getcode());
            baseResponse.setDisp(e.getMessage());
            rsponse( servletResponse, baseResponse);
            log.error("访问异常，异常编号{}，异常代码{}",e.getcode(),e.getMessage());
        }
        catch (Exception e){
            e.printStackTrace();
            baseResponse.setCode(300);
            baseResponse.setDisp("发生错误请重新登录");
            rsponse( servletResponse, baseResponse);
        }

    }


    @Override
    public void destroy() {

    }

    /**
     * 返回异常结果
     *
     * @param servletResponse
     * @param baseResponse
     */
    public void rsponse(ServletResponse servletResponse, BaseRespose baseResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(JSON.toJSONString(baseResponse));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    /***
     * 获取 request 中 json 字符串的内容
     *
     * @param request
     * @return : <code>byte[]</code>
     * @throws IOException
     */
    public static String getRequestJsonString(HttpServletRequest request)
            throws IOException {
        String submitMehtod = request.getMethod();
        // GET
        if (submitMehtod.equals("GET")) {
            return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
            // POST
        } else {
            return getRequestPostStr(request);
        }
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }
}
